"""Weather routes."""
from flask import request, current_app
from flask_restx import Namespace, Resource, fields
from datetime import datetime
from app.models.location import Location
from app.utils.error_handler import ErrorResponse
from app.routes.mock_data import MOCK_WEATHER

api = Namespace('weather', description='Weather operations')

# Models
location_model = api.model('Location', {
    'latitude': fields.Float(required=True),
    'longitude': fields.Float(required=True),
    'accuracy': fields.Float(required=True)
})


def get_mock_weather():
    """Return mock weather data for development/fallback."""
    return {
        **MOCK_WEATHER,
        'timestamp': datetime.now().isoformat()
    }


@api.route('/current')
class CurrentWeather(Resource):
    """Current weather endpoint."""
    
    def get(self):
        """Get current weather.
        
        Validates: Requirements 1.2, 5.1
        """
        # Get location from query parameters
        latitude = request.args.get('latitude', type=float)
        longitude = request.args.get('longitude', type=float)
        accuracy = request.args.get('accuracy', type=float, default=10.0)
        
        if latitude is None or longitude is None:
            api.abort(400, 'latitude and longitude are required')
        
        # Validate location
        try:
            location = Location(
                latitude=latitude,
                longitude=longitude,
                accuracy=accuracy
            )
        except Exception as e:
            api.abort(400, f'Invalid location data: {str(e)}')
        
        # Try to get real weather data, fallback to mock data
        try:
            from app.services.weather_service import WeatherService
            
            qweather_key = current_app.config.get('QWEATHER_KEY')
            redis_url = current_app.config.get('REDIS_URL')
            cache_duration = current_app.config.get('WEATHER_CACHE_DURATION_SECONDS', 1800)
            
            if qweather_key and redis_url:
                weather_service = WeatherService(qweather_key, redis_url, cache_duration)
                weather_data = weather_service.get_current_weather(location)
                
                return {
                    'success': True,
                    'weather': {
                        'temperature': weather_data.temperature,
                        'condition': weather_data.condition,
                        'humidity': weather_data.humidity,
                        'wind_speed': weather_data.wind_speed,
                        'aqi': weather_data.aqi,
                        'timestamp': weather_data.timestamp.isoformat()
                    }
                }, 200
        except Exception as e:
            current_app.logger.warning(f'Weather service failed, using mock data: {e}')
        
        # Return mock weather data as fallback
        return {
            'success': True,
            'weather': get_mock_weather(),
            'is_mock': True
        }, 200


@api.route('/check')
class CheckWeather(Resource):
    """Check weather suitability endpoint."""
    
    def get(self):
        """Check if weather is suitable for walking.
        
        Validates: Requirements 1.2, 5.1, 5.2
        """
        # Get location from query parameters
        latitude = request.args.get('latitude', type=float)
        longitude = request.args.get('longitude', type=float)
        accuracy = request.args.get('accuracy', type=float, default=10.0)
        
        if latitude is None or longitude is None:
            api.abort(400, 'latitude and longitude are required')
        
        # Validate location
        try:
            location = Location(
                latitude=latitude,
                longitude=longitude,
                accuracy=accuracy
            )
        except Exception as e:
            api.abort(400, f'Invalid location data: {str(e)}')
        
        # Try to get real weather data, fallback to mock data
        try:
            from app.services.weather_service import WeatherService
            
            qweather_key = current_app.config.get('QWEATHER_KEY')
            redis_url = current_app.config.get('REDIS_URL')
            cache_duration = current_app.config.get('WEATHER_CACHE_DURATION_SECONDS', 1800)
            
            if qweather_key and redis_url:
                weather_service = WeatherService(qweather_key, redis_url, cache_duration)
                weather_data = weather_service.get_current_weather(location)
                is_suitable, warning_message = weather_service.is_weather_suitable(weather_data)
                
                return {
                    'success': True,
                    'weather': {
                        'temperature': weather_data.temperature,
                        'condition': weather_data.condition,
                        'humidity': weather_data.humidity,
                        'wind_speed': weather_data.wind_speed,
                        'aqi': weather_data.aqi,
                        'timestamp': weather_data.timestamp.isoformat()
                    },
                    'is_suitable': is_suitable,
                    'warning': warning_message
                }, 200
        except Exception as e:
            current_app.logger.warning(f'Weather service failed, using mock data: {e}')
        
        # Return mock weather data as fallback
        return {
            'success': True,
            'weather': get_mock_weather(),
            'is_suitable': True,
            'warning': None,
            'is_mock': True
        }, 200
